package com.andaily.domain.cooking.settlement;

import com.andaily.domain.AbstractDomain;
import com.andaily.domain.cooking.CookingAccountRepository;
import com.andaily.domain.cooking.CookingUserGroup;
import com.andaily.domain.user.User;
import com.andaily.web.context.BeanProvider;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 结算
 *
 * @author Shengzhao Li
 */
public class CookingSettlement extends AbstractDomain {

    private static CookingAccountRepository repository() {
        return BeanProvider.getBean(CookingAccountRepository.class);
    }

    private User creator;
    private CookingUserGroup userGroup;
    private BigDecimal totalAmount = BigDecimal.ZERO;

    private List<UserSettlement> userSettlements = new ArrayList<UserSettlement>();

    private List<SettlementCookingAccount> accounts = new ArrayList<SettlementCookingAccount>();

    public CookingSettlement() {
    }

    public BigDecimal averageAmount() {
        if (userSettlements.isEmpty()) {
            return totalAmount;
        }
        return totalAmount.divide(new BigDecimal(userSettlements.size()), 2, BigDecimal.ROUND_HALF_EVEN);
    }

    public CookingSettlement(BigDecimal totalAmount) {
        this.totalAmount = totalAmount;
    }

    public BigDecimal totalAmount() {
        return totalAmount;
    }

    public List<UserSettlement> userSettlements() {
        return userSettlements;
    }

    public List<SettlementCookingAccount> accounts() {
        return accounts;
    }

    public void save() {
        repository().saveSettlement(this);
        CookingSettlement existSettlement = repository().findSettlementByGuid(this.guid());
        repository().saveUserSettlements(existSettlement, this.userSettlements);
        repository().saveSettlementCookingAccounts(existSettlement, this.accounts);
    }
}
